package com.news.activity;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.xiang.news.R;
import com.news.contant.Contant;
import com.news.db.MyDBAdapter;
import com.news.db.comom.RssContent;
import com.news.util.NetUtil;
import com.news.view.TittleListAdapter;
import com.rss.data.RssFeed;
import com.rss.data.RssItem;
import com.rss.sax.RssHandler;

public class MainActivity extends Activity implements OnClickListener {
	private String RssURL = "http://rss.sina.com.cn/news/marquee/ddt.xml";
	private RssFeed feed;
	private TittleListAdapter adapter;

	private String[] columnName = Contant.columnName;// = { "新闻要闻",
														// "国内要闻","体育要闻汇总" };
	private String columnId = "";
	private String[] columnURL = Contant.columnURL;

	private ListView list_Tittle_List; // 文章列表
	// private Spinner spinner_column;// 栏目
	private TextView txv_error;
	private ImageView img_share;
	private ImageView img_user;

	public static myHandler handler;
	private ProgressDialog progressDialog;

	private List<Map<String, Object>> tittle_List;
	private List<RssContent> rss_List;

	// 栏目菜单
	private PopupWindow menu;
	private LayoutInflater inflater;
	private View layout;
	private Button btn_cloumn_menu;

	MyDBAdapter db = new MyDBAdapter(this);

	private long exitTime = 0;// 再按一次返回键退出程序使用

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		handler = new myHandler();

		// 实例化PopupWindow创建菜单
		initMenu();

		img_share = (ImageView) findViewById(R.id.main_img_share);
		img_user = (ImageView) findViewById(R.id.main_img_user);
		img_share.setOnClickListener(this);
		img_user.setOnClickListener(this);
		list_Tittle_List = (ListView) findViewById(R.id.main_list_tittlelist);
		txv_error = (TextView) findViewById(R.id.main_txv_errorshow);
		btn_cloumn_menu = (Button) findViewById(R.id.main_btn_cloumn_menu);
		btn_cloumn_menu.setOnClickListener(this);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, columnName);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		list_Tittle_List.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		list_Tittle_List.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(MainActivity.this,
						ContentDetailActivity.class);
				Bundle bundle = new Bundle();

				bundle.putString(RssItem.TITLE, (String) tittle_List.get(arg2)
						.get(RssItem.TITLE));
				// bundle.putString(RssItem.TITLE,
				// feed.getItem(arg2).getTitle());
				bundle.putString(RssItem.LINK, feed.getItem(arg2).getLink());
				// bundle.putString(RssItem.LINK, feed.getItem(arg2).getLink());
				bundle.putString(RssItem.PUBDATE, (String) tittle_List
						.get(arg2).get(RssItem.PUBDATE));
				bundle.putString("startTag", Contant.STARTTAG);
				bundle.putString("endTag", Contant.ENDTTAG);

				intent.putExtra("RssFeed", bundle);
				startActivity(intent);
				
//				db.open();
//				db.insertIsRead(feed.getItem(arg2).getLink());
//				db.close();
			}
		});

		initRss();// 刚进入时初始化数据
	}
	@Override
	protected void onResume() {
		super.onResume();
		getListFromDB();//从数据库获取数据
		refleshRss();
	}

	/**
	 * 刚进入时初始化数据
	 */
	private void initRss() {
		RssURL = columnURL[0];
		columnId = Contant.columnID[0];
		btn_cloumn_menu.setText(columnName[0]);
	}

	private void refleshRss() {
		progressDialog = ProgressDialog.show(this, "正在加载", " 正在努力为您获取文章列表……",
				true, true);

		new Thread() {
			@Override
			public void run() {
				super.run();
				feed = getFeed(RssURL);
				Message msg = new Message();
				msg.what = Contant.GET_RSS_TIITLE_LIST_SUCCESS;
				handler.sendMessage(msg);
			}
		}.start();

	}

	// 从数据库刷新文章列表
	private void getListFromDB() {
		db.open();
		tittle_List = db.getTitleFromDB(columnId);
		db.close();
		showListView(tittle_List);
	}

	// 从RSS源上刷新文章列表
	private void getListFromWeb() {
		if (feed == null) {
			txv_error.setVisibility(View.VISIBLE);
			return;
		} else {
			txv_error.setVisibility(View.GONE);
		}

		List<Map<String, Object>> list_fromDB = null;
		if (tittle_List != null) {
			list_fromDB = new ArrayList<Map<String, Object>>(tittle_List);
		}

		tittle_List = feed.getAllItemsForListView();

		// 插入数据库

		db.open();
		// long id;
		// id = db.insertTitle( tittle_List , columnId);
		db.insertTitle(tittle_List, columnId);
		// db.delTitle();//删除后面大于25的数据
		db.close();

		if (list_fromDB != null) {
			Iterator iter = list_fromDB.iterator();
			while (iter.hasNext()) {
				Map<String, Object> map = (Map<String, Object>) iter.next();
				tittle_List.add(map);
			}
		}

		// 显示列表
		showListView(tittle_List);
	}

	/**
	 * 显示文章列表
	 */
	private void showListView(List<Map<String, Object>> tittle_List) {
		// if (feed == null) {
		// txv_error.setVisibility(View.VISIBLE);
		// return;
		// } else {
		// txv_error.setVisibility(View.GONE);
		// }
		//
		// tittle_List = feed.getAllItemsForListView();
		// // 插入数据库
		// MyDBAdapter db = new MyDBAdapter(this);
		// db.open();
		// // long id;
		// // id = db.insertTitle( tittle_List , columnId);
		// db.insertTitle( tittle_List , columnId);
		// db.delTitle();//删除后面大于25的数据
		// db.close();

		if (adapter == null) {
			adapter = new TittleListAdapter(this, tittle_List);
			list_Tittle_List.setAdapter(adapter);
		} else {
			adapter.resetData(tittle_List);
		}
		adapter.notifyDataSetChanged();
		list_Tittle_List.setSelection(0);// 从开头显示

		// setSelection(0);
	}

	private RssFeed getFeed(String urlString) {
		try {
			URL url = new URL(urlString);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlReader = parser.getXMLReader();

			RssHandler rssHandler = new RssHandler();
			xmlReader.setContentHandler(rssHandler);

			InputStream in = new BufferedInputStream(url.openStream());
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");

			// InputSource is = new InputSource(url.openStream(),"GB2312");
			// System.out.println(is.toString());
			xmlReader.parse(new InputSource(isr));

			return rssHandler.getFeed();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	class myHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			if (menu.isShowing()) {
				// menu.setFocusable(false);
				menu.dismiss();
			}
			if (msg.what == Contant.GET_RSS_TIITLE_LIST_SUCCESS) {
				if (NetUtil.isNetAvailable(MainActivity.this)) {
					getListFromWeb();
				} else {
					menu.dismiss();
					Toast.makeText(MainActivity.this, "无网络连接",
							Toast.LENGTH_SHORT).show();
				}
				// showListView();
			}

		}
	}

	// 实例化PopupWindow创建菜单
	private void initMenu() {

		// 获取LayoutInflater实例
		inflater = getLayoutInflater();
		// 获取弹出菜单的布局
		layout = inflater.inflate(R.layout.popmenu, null);
		// 设置popupWindow的布局
		menu = new PopupWindow(layout, WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		menu.setFocusable(true);

		ListView columnList = (ListView) layout
				.findViewById(R.id.pop_list_showcolumn);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.popitems, columnName);
		columnList.setAdapter(adapter);
		columnList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				columnId = Contant.columnID[arg2];
				RssURL = columnURL[arg2];
				btn_cloumn_menu.setText(columnName[arg2]);
				refleshRss();
			}
		});
		//
		menu.getContentView().setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				menu.setFocusable(false);
				menu.dismiss();
				return true;
			}
		});

		// ListView利用setOnKeyListener对menu里的ListView 设置监听代码如下：
		columnList.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				menu.dismiss();
				return false;
			}

		});
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (menu.isShowing()) {
			menu.dismiss();
		}
		return super.onTouchEvent(event);
	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {
		case R.id.main_btn_cloumn_menu:
			if (!menu.isShowing()) {
				menu.setFocusable(true);
				menu.showAsDropDown(v, 10, 0);
			} else {
				menu.dismiss();
			}
			break;
		// 友盟 分享
		case R.id.main_img_share:
			// UMServiceFactory.shareTo( this, SHARE_MEDIA.RENREN,
			// "我使用了快速分享接口（UMServiceFactory.share）", null);
//			UMSocialService controller = UMServiceFactory.getUMSocialService(
//					"test………", RequestType.SOCIAL);
//			controller.openShare(this, false);
			break;
		// 友盟 用户
		case R.id.main_img_user:
//			UMServiceFactory.getUMSocialService("test………", RequestType.SOCIAL)
//					.openUserCenter(this, null);
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if (System.currentTimeMillis() - exitTime > 2000) {
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				this.finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
